package Test;

import javax.naming.ldap.SortKey;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo {

    ServerSocket serverSocket = null;

    public Demo(int p) throws IOException {
        serverSocket = new ServerSocket(p);

    }

    public void start() throws IOException {
        System.out.println("服务器上线");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true) {
            Socket s = serverSocket.accept();

            executorService.submit(() -> {
                poccess(s);

            });

        }

    }

    private void poccess(Socket s) {

        try (InputStream inputStream = s.getInputStream();
             OutputStream outputStream = s.getOutputStream()) {

            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                if (!scanner.hasNext()) {
                    System.out.println("客户端下线");
                    break;
                }
                String s1 = scanner.next();
                String s2 = respond(s1);
                printWriter.println(s2);
                printWriter.flush();
                System.out.printf("[%s:%d] req:%s resp:%s",s.getInetAddress(), s.getPort(),s1, s2);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public String respond(String s1) {
        return s1;
    }

    public static void main(String[] args) throws IOException {

        Demo d = new Demo(9099);
        d.start();

    }
}
